import os
import socket
import subprocess
import time
import queue
from datetime import datetime

sce_number = "0001"     # 景区编号
pro_number = "02"       # 项目编号

cut_path  = "/home/avs/vlog/cut"

# aliyun docker 的 /home 目录挂载在 aliyun 的 /mnt/videos 目录下
ecs_path    = "/home"               # 北大信研院服务器视频上传路径
ecs_user    = "root"                # 北大信研院服务器用户名
ecs_address = "115.236.53.230"      # 北大信研院服务器地址
tcp_address = "115.236.53.230"      # 北大信研院服务器地址
tcp_port    = 6667                  # 北大信研院服务器 TCP 通信端口

queue_videos = queue.Queue()

def send_tcp(dir_name, filename):
    try:
        sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        server_address = (tcp_address, tcp_port)
        sock.connect(server_address)
        message_ori=dir_name+'?'+filename+'?'+sce_number+'?'+pro_number # ip+文件名+景区编号+项目编号
        message_b =bytes(message_ori, encoding='utf-8')
        sock.sendall(message_b)
    except socket.error as e:
        print(f"Connection failed: {e}")
    finally:
        sock.close()

def send_video_and_tcp():
    while True:
        if(queue_videos.empty()):
            break

        src_file = queue_videos.get()
        mp4_file_name = os.path.basename(src_file)
        mp4_dir_name = os.path.basename(os.path.dirname(src_file))
        dst_file = ecs_user + "@" + ecs_address + ":" + ecs_path + "/" + sce_number + "/" + pro_number + "/" + mp4_dir_name + "/" + mp4_file_name
        command = ["scp", "-P 6666", src_file, dst_file]
        # print(command)

        result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if result.returncode == 0:
            print(datetime.now(), mp4_dir_name, mp4_file_name, "upload!")
            send_tcp(mp4_dir_name, mp4_file_name)
            os.remove(src_file)
        else:
            print("error:", command, result.stderr.decode())
            queue_videos.put(src_file)

def get_files(directory):
    """
    Retrieve all file names in a specified directory.

    :param directory: str, the target directory path.
    :return: list, a list of file paths in the directory.
    """
    files = []
    for f in os.listdir(directory):
        path = os.path.join(directory, f)
        if os.path.isfile(path):
            files.append(path)
    return files

def get_subdirs(directory):
    """
    Retrieve all subdirectory names in a specified directory.

    :param directory: str, the target directory path.
    :return: list, a list of subdirectory paths in the directory.
    """
    subdirs = []
    for f in os.listdir(directory):
        path = os.path.join(directory, f)
        if os.path.isdir(path):
            subdirs.append(path)
    return subdirs

def find_mp4_files(files):
    """
    Filter and return all files that have a '.mp4' extension from the given file list.

    :param files: list, a list of file paths.
    :return: list, a list of file paths that end with '.mp4'.
    """
    mp4_files = []
    for file in files:
        if file.endswith('.mp4'):
            mp4_files.append(file)
    return mp4_files

def main():
    # 设置裁剪好的视频存放位置
    parent_dir = cut_path

    while True:
        subdirs = get_subdirs(parent_dir)

        for subdir in subdirs:
            # print("subdir:", subdir)

            files = get_files(subdir)
            mp4s = find_mp4_files(files)

            for f in mp4s:
                # print("mp4   :", f)
                queue_videos.put(f);

        send_video_and_tcp()

        if(queue_videos.empty()):
            time.sleep(5)

if __name__=="__main__":
    main()